from flask import Blueprint,render_template,request,jsonify, url_for,current_app,session
from werkzeug.utils import secure_filename
from apps.views import login
import os
from exts import db
import uuid
import time
from datetime import datetime
#from ..utils.token import token_required,decode_token
from flask_jwt_extended import create_access_token, jwt_required, JWTManager, get_jwt_identity
from ..models.User import User
from ..models.Op import Op
from ..models.Originimage import Originimage
from ..models.Afteropimage import Afteropimage


wm = Blueprint('watermark',__name__)

# 允许的文件扩展名
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@wm.route('/upload', methods=['POST'])
@jwt_required()
def upload_file():
    #token解码
    username=get_jwt_identity()
    user = User.query.filter_by(userName=username).first()
    userId=user.userId
    print('username:'+username)
    if 'image' not in request.files:
        return jsonify({"error": "No file part in the request"}), 400

    file = request.files['image']
    if file.filename == '':
        return jsonify({"error": "No selected file"}), 400

    #可能存在的bug
    #重名的文件会覆盖原来的文件
    if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)

        # 获取当前时间戳，并格式化成字符串
        timenow=datetime.now()
        print(timenow)
        timestamp = time.strftime('%Y%m%d%H%M%S')
        # 构建新文件名
        new_filename = f"{timestamp}_{filename}"
        process_filename=f"WRM_{timestamp}_{filename}"
        print(new_filename)
        print(file.filename)
        print(filename)

        file_path = os.path.join(current_app.root_path,current_app.config['UPLOAD_FOLDER'], new_filename)
        file.save(file_path)
        extension =file.filename.rsplit('.', 1)[1].lower()
        print("extension",extension)
        file_name = file.filename.rsplit('.', 1)[0]
        print("file_name",file_name)
        file.seek(0)
        process_file_path = os.path.join(current_app.root_path, current_app.config['PROCESSED_FOLDER'], process_filename)
        file.save(process_file_path)


        print("file_path", file_path)
        print("process_file_path", process_file_path)
        time.sleep(5)


        file_url = url_for('static', filename='processed/' + process_filename)

        #向originimage插入数据
        origin_image = Originimage(imageName=new_filename,imageType=extension,imagePath=file_path,uploadTime=timestamp)
        # 向afteropimage插入数据
        process_image=Afteropimage(imageName=process_filename,imagePath=process_file_path,createtime=timestamp,imageType=extension)
        db.session.add(origin_image)
        db.session.add(process_image)
        db.session.commit()

        # 生成一个新的 UUID
        new_uuid = uuid.uuid4().hex

        # 转换为字符串形式
        uuid_str = str(new_uuid)
        #向op表插入数据
        op = Op(opId=uuid_str,userId=userId, originImageId=origin_image.imageId, afterOpImageId=process_image.id)
        db.session.add(op)
        db.session.commit()
        print("1111")
        print(file_url)
        return jsonify({"processedImageURL":file_url }), 200
    else:
        return jsonify({"error": "File type not allowed"}), 400

@wm.route('/watermark')
def watermark_view():
    username = session.get('user_name', None)
    print(username)
    return render_template('watermark.html',username=username)


